const Vue = require('vue')
const express=require('express');
const server = require('express')();
const serialize = require('serialize-javascript')
const renderer = require('vue-server-renderer').createRenderer({
    template: require('fs').readFileSync('./template/index.html', 'utf-8')
})
var morgan = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser=require('body-parser')
var MongoStore = require('connect-mongo')(session);
var config = require("./config/index");
var connect=require('./mongodb/mongodb.js');
var multipart = require('connect-multiparty');

//https://ssr.vuejs.org/zh/guide/routing.html#%E4%BD%BF%E7%94%A8-vue-router-%E7%9A%84%E8%B7%AF%E7%94%B1
server.use(morgan('short'));
server.use(express.static('public'));
server.use(multipart());
server.use(bodyParser.urlencoded({ limit: '50mb',extended: false }))
server.use(bodyParser.json({limit: '50mb'}))
server.use(cookieParser());

server.use(session({
    secret:config.cookieSecret,
    key:config.dbName,
    cookie:{maxAge:1000*60*60*24*1},
    resave:true,
    saveUninitialized:true,
    store:new MongoStore({url:config.mongodb})
}));


var router=require('./router/index');
connect(()=>{
  router(server);
  server.get('*', (req, res) => {
    const createApp = require('./public/bundle.server.js').default;
    const context = {
      title: 'hello',
      meta: `
        <meta >
        <meta >
      `
    }
      context.url=req.url;
      context.user=req.session.user || {};
      //参数2是给模板的对象
      createApp(context).then(app => {
          if (context.initialState) {
              context.ins=serialize(context.initialState, { isJSON: true })
          }
          renderer.renderToString(app,context, (err, html) => {
            
            if (err) {
              if (err.code === 404) {
                res.status(404).end('Page not found')
              }else{
                res.status(500).end('Internal Server Error')
              }
            } else {
              res.end(html)
            }
          })
      }).catch(err=>{
        if(err.code==302){
          res.redirect(err.message);
        }else{
          res.status(err.code).send(err.message);
        }
      })
  });
})


server.listen(8081)